<?php
ob_start();
set_time_limit(0);
define('CRON_JOB',true);

if ($rFile = @fopen($sLockFile = join(DIRECTORY_SEPARATOR,array(dirname(__FILE__),'..','www','.htaccess')),'r')) {
	if ($argc > 1 || flock($rFile,LOCK_EX | LOCK_NB)) {
		echo date('r')." Cron work started...\n";
		require join(DIRECTORY_SEPARATOR,array(dirname(__FILE__),'..','www','index.php'));
		Zend_Controller_Front::getInstance()->setParam('bootstrap',Zend_Registry::get('bootstrap'));

		if ($rDir = opendir($sModulesPath = dirname(__FILE__).DIRECTORY_SEPARATOR.'modules')) {
			while ($sModule = readdir($rDir)) {
				if (is_dir($sPath = $sModulesPath.DIRECTORY_SEPARATOR.$sModule) && $sPath[0] != '.') {
					if (isset($argv[1]) && $argv[1] != $sModule) {
						continue;
					}

					if (@include(join(DIRECTORY_SEPARATOR,array($sPath,'controllers','CronController.php')))) {
						try {
							$sControllerClass = ucfirst($sModule).'_CronController';

							$oRequest = Zend_Controller_Front::getInstance()->getRequest();
							$oRequest->setModuleName($sModule);
							$oRequest->setDispatched(true);
							$oResponse = Zend_Controller_Front::getInstance()->getResponse();

							$oController = new $sControllerClass($oRequest,$oResponse);
							$oController->dispatch((isset($argv[2]) ? $argv[2] : 'index').'Action');

							$oResponse->sendResponse();
						}
						catch (Exception $oException) {
							echo $oException->getMessage()."\n".$oException->getTraceAsString()."\n";
						}
					}
				}
			}
		}

		if ($argc < 2) {
			flock($rFile,LOCK_UN);
		}
	}
	else {
		echo date('r')." Cron work skiped.\n";
	}

	fclose($rFile);
}
else {
	echo date('r')." Can not open file $sLockFile for read. Cron work skiped.\n";
}

ob_end_flush();
?>